<?php
namespace app\home\controller;

use nekoing\BaseController;
use nekoing\AppException;
use nekoing\ErrorCode;
use app\home\validate\UserValidate;

class User extends BaseController
{

    public function register()
    {
        $data = [
            'username' => input('post.username'),
            'password' => input('post.password'),
            'nickname' => input('post.nickname'),
            'email' => input('post.email')
        ];
        
        $validate = new UserValidate();
        if (! $validate->check($data)) {
            $this->ajaxFail(ErrorCode::INVALID_PARAM, $validate->getError());
        }
        
        $user = new \app\home\model\User();
        if ($user->save($data)) {
            $this->ajaxSuccess();
        } else {
            $this->ajaxFail(ErrorCode::UNKOWN);
        }
    }

    public function info($openid)
    {
        $user = $this->getUser($openid);
        $this->ajaxSuccess([
            'user' => $user->getShowData()
        ]);
    }

    /**
     *
     * @param string $openid
     * @throws AppException
     * @return \app\home\model\User
     */
    protected function getUser($openid)
    {
        $model = \app\home\model\User::get([
            'openid' => $openid
        ]);
        if (! $model) {
            throw new AppException(ErrorCode::DATA_NOT_EXISTS);
        }
        
        return $model;
    }
}

?>